package Controller;



import java.awt.print.PrinterException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;


public class Log {

	private static String logpath,logpathpdf,readed;
	private static File logfile,logfilepdf;
	private static FileWriter fw;
	private static FileReader fr;
	private static BufferedReader br;
	private static FileOutputStream os;
	private static Document doc;
	private static PdfWriter pdfw;


	
	
	
	public Log(){
		
	}
	
	public static void init(String path){
		
		
		
		logpath=path;
		logfile= new File(logpath);
		
		readed=null;
		try {
			
			fw= new FileWriter(logfile,true);

			
			
		} catch(Exception ex) {
			
			ex.printStackTrace();
			
		}
		
	}
	
	public static void initExport() throws FileNotFoundException{
		logpathpdf=logpath.split("\\.")[0]+".pdf";
		logfilepdf= new File(logpathpdf);
		
		os= new FileOutputStream(logfilepdf);
		
		fr=new FileReader(logfile);
		br=new BufferedReader(fr);
		doc=new Document();
	}
	
	public static void setLogPath(String path){
		logpath=path;
	}
	
	public static String getLogPath(){
		return logpath;
	}
	
	public static void doLog(String code, String text) throws IOException{
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd - HH:mm:ss ");
        java.util.Date currentTime = new java.util.Date();       
		
        fw.write(code+" "+text+" "+formatter.format(currentTime)+"\n");
        fw.flush();
	}
	
	
	public static void exportLog() throws IOException, DocumentException{

		PdfWriter.getInstance(doc, os);
		doc.open();
		
		Thread t= new Thread(){
			
			public void run(){
				try {
					
					
					while ((readed = br.readLine()) != null){
						 doc.add(new Paragraph(readed));
					}
					
					
				} catch (IOException | DocumentException e) {
					e.printStackTrace();
				}
				if(readed == null){
					doc.close();
					try {
						os.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			
		};
		
		t.start();
		
		
		
	}
	
}
